package com.tokenplus.thai.checkin

import android.annotation.SuppressLint
import android.app.ActionBar.LayoutParams
import android.os.Handler
import android.os.Looper
import android.view.View
import android.view.animation.AlphaAnimation
import android.view.animation.Animation
import android.view.animation.Animation.AnimationListener
import android.widget.RelativeLayout
import android.widget.Toast
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.tokenplus.thai.R
import com.tokenplus.thai.base.BaseActivity
import com.tokenplus.thai.aviewmodel.CheckinViewModel
import com.tokenplus.thai.checkin.adapter.CheckinDayAdapter
import com.tokenplus.thai.components.toast.CheckinSuccessToast
import com.tokenplus.thai.data.ReqBase
import com.tokenplus.thai.databinding.ActivityCheckinBinding
import com.tokenplus.thai.enums.PageTagEnum
import com.tokenplus.thai.extend.toFinanceString
import com.tokenplus.thai.home.repo.HomeCoinManager

/** coupons页 */
@SuppressLint("CustomSplashScreen,NotifyDataSetChanged")
class CheckinActivity : BaseActivity() {

    //布局binding
    private lateinit var mBinding: ActivityCheckinBinding

    //适配器
    private lateinit var mCheckinWeekAdapter: CheckinDayAdapter
    private lateinit var mCheckinDayAdapter: CheckinDayAdapter

    //home viewModel
    private val mCheckinViewModel by lazy {
        ViewModelProvider(this)[CheckinViewModel::class.java]
    }

    override fun onBindingViewModel(): List<ViewModel> {
        val list = mutableListOf<ViewModel>()
        list.add(mCheckinViewModel)
        return list
    }

    override fun onBindingViewTag(): String {
        return PageTagEnum.coupons.name.uppercase()
    }

    override fun onBindingContentView(): View {
        mBinding =
            ActivityCheckinBinding.inflate(layoutInflater)
        return mBinding.root
    }

    override fun onContentViewBinded() {
        try {
            //初始化刷新组件
            initRefreshUI()

            //监听返回
            onHandleLiveDataCallback()

            //初始化适配器
            mCheckinWeekAdapter = CheckinDayAdapter(mCheckinViewModel.mWeekList)
            mCheckinWeekAdapter.setItemClickListener {}

            mBinding.listWeek.layoutManager = GridLayoutManager(this, 7)
            mBinding.listWeek.adapter = mCheckinWeekAdapter

            //初始化适配器
            mCheckinViewModel.mDayList.clear()
            mCheckinDayAdapter = CheckinDayAdapter(mCheckinViewModel.mDayList)
            mCheckinDayAdapter.setItemClickListener {
                checkin()
            }

            mBinding.listDays.layoutManager = GridLayoutManager(this, 7)
            mBinding.listDays.adapter = mCheckinDayAdapter

            mBinding.checkIn.setOnClickListener {
                if (mCheckinViewModel.onTodayDidCheckinLiveData.value == true) {
//                    Toast.makeText(
//                        this@CheckinActivity,
//                        getString(R.string.check_in7),
//                        Toast.LENGTH_SHORT
//                    ).show()

                    showCheckinSuccessToast()

                } else {
                    checkin()
                }
            }

            // 获取签到信息
            getCheckinDetail()

        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /** 监听live data 返回 */
    @SuppressLint("NotifyDataSetChanged", "SetTextI18n")
    private fun onHandleLiveDataCallback() {
        mCheckinViewModel.onGetCheckinDetailLiveData.observe(this) {
            stopRefreshState()
            if (it.isSuccess) {
                it.getOrNull()?.let { result ->
                    mCheckinViewModel.updateCheckinDetail(result)
                    mCheckinDayAdapter.notifyDataSetChanged()

                    mBinding.month.text = mCheckinViewModel.mCurMonth
                    mBinding.checkinEarnAmount.text = result.totalIncome.toFinanceString() + " USDT"
                    mBinding.checkIn.text = getString(R.string.check_in2, result.dayIncome ?: "")
                }
            }
        }

        mCheckinViewModel.onCheckinLiveData.observe(this) {
            stopRefreshState()
            if (it.isSuccess) {
                mCheckinViewModel.todayDidShowCheckinRemindDialog()
//                Toast.makeText(
//                    this@CheckinActivity,
//                    "+${mCheckinViewModel.mCheckinDayIncome}",
//                    Toast.LENGTH_SHORT
//                ).show()
                try {
                    showCheckinSuccessToast()
                } catch (e: Exception) {
                    e.printStackTrace()
                }
                getCheckinDetail(false)
            }
        }

        mCheckinViewModel.onTodayDidCheckinLiveData.observe(this) {
//            if (it) {
//                mBinding.checkIn.isEnabled = false
//            } else {
//                mBinding.checkIn.isEnabled = true
//            }
        }
    }

    private fun getCheckinDetail(showLoading:Boolean=true) {
        val reqBase = ReqBase()
        reqBase.showLoading = showLoading
        mCheckinViewModel.getCheckinDetail(reqBase)
    }

    private fun checkin() {
        val reqBase = ReqBase()
        reqBase.showLoading = true
        mCheckinViewModel.checkin(reqBase)
    }

    /** 初始化下拉刷新 */
    private fun initRefreshUI() {
        connectSwipeRefreshLayout(mBinding.swipeRefresh) {
            getCheckinDetail(false)
        }
    }

    private fun showCheckinSuccessToast() {
        // 限制点击
        mBinding.checkIn.isEnabled = false

        val layoutManager = mBinding.listDays.layoutManager as GridLayoutManager
        val itemView =
            layoutManager.findViewByPosition(mCheckinViewModel.curDayItemPosition())
        if (itemView != null) {
            val location = IntArray(2)
            itemView.getLocationInWindow(location)
            val x = location[0]
            val y = location[1]

            val item1 = CheckinSuccessToast(this@CheckinActivity)
            val lp = RelativeLayout.LayoutParams(
                LayoutParams.WRAP_CONTENT,
                LayoutParams.WRAP_CONTENT
            )
            item1.setAmount("+ ${mCheckinViewModel.mCheckinDayIncome}")

            val hPx = 24 * this.resources.displayMetrics.density
            lp.leftMargin = x - 15
            lp.topMargin = y - hPx.toInt()
            item1.setLayoutParams(lp)
            mBinding.checkinRoot.addView(item1)

            // 2秒后解除
            Handler(Looper.getMainLooper()).postDelayed({
                val fadeIn = AlphaAnimation(1f, 0f)
                fadeIn.duration = 1000
                fadeIn.setAnimationListener(object : AnimationListener {
                    override fun onAnimationStart(animation: Animation?) {
                    }

                    override fun onAnimationEnd(animation: Animation?) {
                        item1.visibility = View.GONE
                        mBinding.checkinRoot.removeView(item1)
                        mBinding.checkIn.isEnabled = true
                    }

                    override fun onAnimationRepeat(animation: Animation?) {
                    }
                })
                item1.startAnimation(fadeIn)
            }, 1000)
        }
    }
}